package com.gdca.sdk.ca.utils;

import android.content.Context;
import android.content.pm.PackageManager;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Environment;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class DeviceInfo {
    public static double screenHeight = 0;
    public static double screenWidth = 0;
    public static double dpiX = 0;
    public static double dpiY = 0;
    public static double density = 0;
    public static double densityDpi = 0;
    public static double scaledDensity = 0;
    public static int androidSdk = 0;
    public static String serial = null;
    public static String androidId = null;
    public static String Mac = null;
    public static String deviceId = null;
    public static String Uid = null;
    public static String mainSdCardPath = null;// 内置sd卡路径根目录 /mnt/sdcard
    public static String sdCardCachePath = null;// /mnt/sdcard/Android/data/com.my.app/cache
    public static String sdCardFilePath = null;// /mnt/sdcard/Android/data/com.my.app/file
    public static String appCachePath = null;// /data/data/<application
    // package>/cache
    public static String[] sdCardPaths = null;// 所有sd卡路径
    public static String cameraCachePath = null;// /data/data/<application
    // package>/camera
    public static String databasePath = null;
    public static int maxMenory;
    public static int coreNum = 0;
    public static int statusBarHeight = 0;

    public DeviceInfo() {

    }

    public static void getInstance(Context context) {
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        screenHeight = dm.heightPixels;
        screenWidth = dm.widthPixels;
        dpiX = dm.xdpi;
        dpiY = dm.ydpi;
        density = dm.density;
        densityDpi = dm.densityDpi;
        scaledDensity = dm.scaledDensity;
        androidSdk = Build.VERSION.SDK_INT;
        serial = Build.SERIAL;
        androidId = Settings.Secure.getString(context.getContentResolver(),
                Settings.Secure.ANDROID_ID);
        Mac = getMacAddress(context);
        TelephonyManager manager = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        deviceId = manager.getDeviceId();
//        Uid = getUniqueID();
        List<String> list = new ArrayList<String>();
        mainSdCardPath = Environment.getExternalStorageDirectory().getPath();
        if (context.getExternalCacheDir() != null) {
            sdCardCachePath = context.getExternalCacheDir().getPath();
            cameraCachePath = context.getExternalCacheDir().getParent()
                    + "/camera";
        }
        if (context.getExternalFilesDir(null) != null) {
            sdCardFilePath = context.getExternalFilesDir(null).getPath();
        }
        appCachePath = context.getCacheDir().getPath();
        list.add(mainSdCardPath);
        String rawSecondaryStorage = System.getenv("SECONDARY_STORAGE");
        if (!TextUtils.isEmpty(rawSecondaryStorage)) {
            for (String secondaryPath : rawSecondaryStorage.split(":")) {
                list.add(secondaryPath);
            }
        }
        sdCardPaths = list.toArray(new String[list.size()]);
        coreNum = Runtime.getRuntime().availableProcessors();
        maxMenory = (int) Runtime.getRuntime().maxMemory();

        File file = new File(context.getCacheDir().getParent(), "NenoData");
        if (!file.exists()) {
            file.mkdirs();
        }
        databasePath = file.getPath();

        int resourceId = context.getResources().getIdentifier(
                "status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            statusBarHeight = context.getResources().getDimensionPixelSize(
                    resourceId);
        }
    }

    public static String getDeviceId(Context context) {
//        TelephonyManager manager = (TelephonyManager) context
//                .getSystemService(Context.TELEPHONY_SERVICE);
//        deviceId = manager.getDeviceId();
//        Mac = getMacAddress(context);
        String ANDROID_ID = Settings.System.getString(context.getContentResolver(), Settings.System.ANDROID_ID);
        String SerialNumber = Build.SERIAL;
        String m_szDevIDShort = "35" + //we make this look like a valid IMEI
                Build.BOARD.length() % 10 +
                Build.BRAND.length() % 10 +
                Build.CPU_ABI.length() % 10 +
                Build.FINGERPRINT.length() % 10 +
                Build.DEVICE.length() % 10;
        String m_szLongID = ANDROID_ID + SerialNumber + m_szDevIDShort;
        return EncryptUtils.encryptMD5ToString(m_szLongID).toLowerCase();
    }

//    public static String getUniqueID() {
//        String m_szLongID = deviceId // + getPseudoUniqueID()
//                + androidId // + getMac(context)
//                + Mac;
//        // compute md5
//        MessageDigest m = null;
//        StringBuffer m_szUniqueID = new StringBuffer();
//        try {
//            m = MessageDigest.getInstance("MD5");
//            m.update(m_szLongID.getBytes(), 0, m_szLongID.length());
//            // get md5 bytes
//            byte p_md5Data[] = m.digest();
//            // create a hex string
//
//            for (int i = 0; i < p_md5Data.length; i++) {
//                int b = (0xFF & p_md5Data[i]);
//                // if it is a single digit, make sure it have 0 in front (proper
//                // padding)
//                if (b <= 0xF)
//                    m_szUniqueID.append("0");
//                // add number to string
//                m_szUniqueID.append(Integer.toHexString(b));
//            } // hex string to uppercase
//        } catch (NoSuchAlgorithmException e) {
//            e.printStackTrace();
//        }
//        return m_szUniqueID.toString().toUpperCase();
//    }

    private static String getMacAddress(Context context) {
        String macAddress = "";
        try {
            WifiManager wifiMgr = (WifiManager) context
                    .getSystemService(Context.WIFI_SERVICE);
            WifiInfo info = (null == wifiMgr ? null : wifiMgr
                    .getConnectionInfo());
            if (null != info) {
                macAddress = info.getMacAddress();
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
        return macAddress;
    }

    /**
     * <<<<<<< HEAD
     * 获取手机内存大小
     * =======
     * ��ȡ�ֻ��ڴ��С
     * >>>>>>> a37353c85889279baef20f2dcd06863c4c70ebab
     *
     * @return
     */
    public static long getTotalMemory() {
        String str1 = "/proc/meminfo";// 系统内存信息文件
        String str2;
        String[] arrayOfString;
        long initial_memory = 0;
        try {
            FileReader localFileReader = new FileReader(str1);
            BufferedReader localBufferedReader = new BufferedReader(
                    localFileReader, 8192);
            str2 = localBufferedReader.readLine();// 读取meminfo第一行，系统总内存大小

            arrayOfString = str2.split("\\s+");

            initial_memory = Integer.valueOf(arrayOfString[1]).intValue() * 1024;// 获得系统总内存，单位是KB，乘以1024转换为Byte

            localBufferedReader.close();

        } catch (IOException e) {
        }
        return initial_memory;// Byte转换为KB或者MB，内存大小规格化
    }

    public static boolean hasStorage() {
        String str = Environment.getExternalStorageState();
        return str.equals(Environment.MEDIA_MOUNTED);
    }

    public static int dpToPx(int dp) {
        double result = dp * density + 0.5;
        return (int) result;
    }

    public static int dpToPx(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    public static int pxToDp(int px) {
        double result = px / density + 0.5;
        return (int) result;
    }

    public static int spToPx(int sp) {
        double result = sp * scaledDensity + 0.5;
        return (int) result;
    }

    public static int pxToSp(int px) {
        double result = px / scaledDensity + 0.5;
        return (int) result;
    }

    /**
     * <<<<<<< HEAD
     * 判断设备是否支持多点触控
     * =======
     * �ж��豸�Ƿ�֧�ֶ�㴥��
     * >>>>>>> a37353c85889279baef20f2dcd06863c4c70ebab
     *
     * @param context
     * @return
     */
    public static boolean isSupportMultiTouch(Context context) {
        PackageManager pm = context.getPackageManager();
        boolean isSupportMultiTouch = pm
                .hasSystemFeature(PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH);
        return isSupportMultiTouch;
    }

    /**
     * 获取设备厂商
     * <p>如Xiaomi</p>
     *
     * @return 设备厂商
     */

    public static String getManufacturer() {
        return Build.MANUFACTURER;
    }

    /**
     * 获取设备型号
     * <p>如MI2SC</p>
     *
     * @return 设备型号
     */
    public static String getModel() {
        String model = Build.MODEL;
        if (model != null) {
            model = model.trim().replaceAll("\\s*", "");
        } else {
            model = "";
        }
        return model;
    }

    /**
     * 获取设备系统版本
     *
     * @return
     */
    public static String getAndroidRelease() {
        String version_release = Build.VERSION.RELEASE;
        if (version_release == null) {
            version_release = "";
        }
        return version_release;
    }

}
